#include "fescreenanimation_private.h"

#include <QWidget>

FeScreenAnimation::FeScreenAnimation(QWidget *currentScreen, QWidget *nextScreen, QObject *parent)
: QAbstractAnimation(parent)
{
	Q_ASSERT(currentScreen);
	Q_ASSERT(nextScreen);
	Q_ASSERT(currentScreen->parent() == nextScreen->parent());
	dur = 1000;
	cur_w = currentScreen;
	next_w = nextScreen;
	ec = QEasingCurve(QEasingCurve::Linear);
}

FeScreenAnimation::~FeScreenAnimation()
{
}

int FeScreenAnimation::duration(void) const 
{
	return dur;
}

void FeScreenAnimation::setDuration(int _v)
{
	Q_ASSERT(state() == Stopped);
	dur = _v;
}

QEasingCurve FeScreenAnimation::easingCurve() const
{
	return ec;
}

void FeScreenAnimation::setEasingCurve(const QEasingCurve &easing)
{
	ec = easing;
}

void FeScreenAnimation::updateCurrentTime(int currentTime)
{
	int d = 0;
	const int t = dur / 2;
	Q_ASSERT(t > 0);
	if(currentTime < t)
	{
		qreal n = (qreal)currentTime / (qreal)t;
		d = (int)(geometry.width() * ec.valueForProgress(n));
	}
	else
	{
		if(!next_raised)
		{
			cur_w->stackUnder(next_w);
			next_raised = true;
		}

		qreal n = 1.0 - (qreal)(currentTime - t) / (qreal)t;
		d = (int)(geometry.width() * ec.valueForProgress(n));

	}
	cur_w->move(geometry.x() - d, geometry.y());
	next_w->move(geometry.x() + d, geometry.y());
}

void FeScreenAnimation::updateDirection(QAbstractAnimation::Direction direction) 
{
	Q_ASSERT(direction == Forward);
}

void FeScreenAnimation::updateState(QAbstractAnimation::State newState, QAbstractAnimation::State oldState)
{
	switch(newState)
	{
	case Running:
		if(oldState == Stopped)
		{
			next_raised = false;
			next_w->stackUnder(cur_w);
			geometry = cur_w->geometry();
			next_w->setGeometry(geometry);
			next_w->show();
		}
		break;

	case Stopped:
		if(oldState == Running)
		{
			cur_w->stackUnder(next_w);
			cur_w->setGeometry(geometry);
			next_w->setGeometry(geometry);
			cur_w->hide();
		}
		break;
	}
}